package org.incubator.testing;

import java.util.LinkedHashSet;
import java.util.Set;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;

public abstract class RepeatableMethodReturnAssertion<T> {
    public static final int DEFAULT_ATTEMPTS = 50;
    private final Matcher<? super T> matcher;
    private int attempts = DEFAULT_ATTEMPTS;

    public RepeatableMethodReturnAssertion(Matcher<? super T> matcher) {
        this.matcher = matcher;
    }

    protected void setAttempts(int attempts) {
        this.attempts = attempts;
    }

    protected abstract T invokeMethod();

    public void run() {
        this.run("");
    }

    public void run(String message) {
        Set<T> failed = new LinkedHashSet<T>();
        for (int attempt = 0; attempt < attempts; attempt++) {
            T result = this.invokeMethod();
            if (!matcher.matches(result)) {
                failed.add(result);
            }
        }
        if (!failed.isEmpty()) {
            Description description = new StringDescription();
            if (message != null) {
                description.appendText(message);
            }
            description.appendText("\nExpected: ").appendDescriptionOf(matcher);
            description.appendText("\nBut generated the following unsatisfying values: ");
            description.appendValueList("{", ", ", "}", failed);
            throw new AssertionError(description.toString());
        }
    }

}
